package com.mvc.business.web;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.PdfUtils;
import com.mvc.ProjectUtils;
import com.mvc.base.model.Company;
import com.mvc.base.service.CustomerManager;
import com.mvc.business.model.OrderAssociated;
import com.mvc.business.model.Packing;
import com.mvc.business.service.OrderAssociatedManager;
import com.mvc.business.service.OrderManager;
import com.mvc.business.service.PackingManager;
import com.mvc.config.ApplicationConfig;
import com.mvc.framework.model.BaseEntity;
import com.mvc.framework.service.DictionaryFacade;
import com.mvc.framework.service.PageManager;
import com.mvc.framework.util.FileUpDownUtils;
import com.mvc.framework.util.PageSearch;
import com.mvc.framework.web.PageController;
import com.mvc.portal.service.NotificationManager;
import com.mvc.security.model.User;
import com.mvc.security.service.UserManager;

@Controller
@RequestMapping("packing")
public class PackingController extends PageController<Packing> {

	private static final Logger	   LOGGER	= Logger.getLogger(PackingController.class);

	@Autowired
	private PackingManager	       packingManager;

	@Autowired
	private UserManager<User>	   userManager;

	@Autowired
	private NotificationManager	   notificationManager;

	@Autowired
	private OrderManager	       orderManager;

	@Autowired
	private DictionaryFacade	   dictionaryFacade;

	@Autowired
	private OrderAssociatedManager	orderAssociatedManager;

	@Autowired
	private CustomerManager	       customerManager;

	protected String handlePage(HttpServletRequest request, PageSearch page) {
		request.setAttribute("users", userManager.getAll());
		request.setAttribute("customers", customerManager.getAll());
		request.setAttribute("action", "page");
		return super.handlePage(request, page);
	}

	protected String handleEdit(HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
		if (null == id) {
			Packing entity = new Packing();
			// Invalid object id
			entity.setObjectId(-packingManager.createSystemId());
			request.setAttribute("entity", entity);
		} else {
			Packing entity = getEntityManager().get(id);
			request.setAttribute("entity", entity);
			request.setAttribute("orderNo", orderAssociatedManager.getPackingOrderStr(entity.getObjectId()));
		}
		request.setAttribute("units", dictionaryFacade.getDictionariesByDictionaryId(1008));
		request.setAttribute("template", ApplicationConfig.getTemplate());
		return getFileBasePath() + "editPacking";
	}

	protected String handleSave(HttpServletRequest request, ModelMap modelMap, Packing order) throws Exception {
		getEntityManager().save(order);
		return "redirect:edit/" + ((BaseEntity) order).getId() + getMessage("common.base.success", request) + "&action="
		        + request.getParameter("action");
	}

	@RequestMapping("print/{orderId}")
	public String print(HttpServletRequest request, @PathVariable Integer orderId) {
		Map<String, Object> model = prepareOrderData(orderId, request);
		String orderContent = notificationManager.getTemplateString("packing.html", model);
		request.setAttribute("orderContent", orderContent);
		return getFileBasePath() + "printPacking";
	}

	@RequestMapping("notify/{orderId}")
	public String notify(@PathVariable Integer orderId, String purchasers, Boolean customer, ModelMap modelMap, HttpServletRequest request) {
		boolean result = false;
		try {
			String userEmails = purchasers;
			userEmails += ProjectUtils.EMAIL_SPLIT + request.getParameter("others");
			if (StringUtils.isNotBlank(userEmails) || customer) {
				Map<String, Object> model = prepareOrderData(orderId, request);
				String orderContent = notificationManager.getTemplateString("packing.html", model);
				Packing order = (Packing) model.get("entity");
				if (customer) {
					userEmails += ProjectUtils.EMAIL_SPLIT + order.getCustomer().getEmail();
				}
				String[] to = ProjectUtils.getMailTo(userEmails);
				if (to != null && to.length > 0) {
					Company company = order.getCompany();
					String header = ProjectUtils.getPdfHeader(company);
					String footer = ProjectUtils.getPdfFooter(company);
					File file = PdfUtils.htmlToPdf(orderContent, header, footer);
					String subject = "Packing List(" + company.getName() + ":" + order.getNo() + ")";
					notificationManager.sendMail(subject, ProjectUtils.getENNoReplyMessage(), new File[] { file },
					        new String[] { order.getNo() + ".pdf" }, to, new String[] {}, true);
					result = true;
				}
			}
		} catch (Exception e) {
			LOGGER.error("notify", e);
		}
		modelMap.addAttribute("result", result);
		return "jsonView";
	}

	@RequestMapping("download/{orderId}")
	public String download(@PathVariable Integer orderId, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> model = prepareOrderData(orderId, request);
			String orderContent = notificationManager.getTemplateString("packing.html", model);
			Packing order = (Packing) model.get("entity");
			Company company = order.getCompany();
			String header = ProjectUtils.getPdfHeader(company);
			String footer = ProjectUtils.getPdfFooter(company);
			File file = PdfUtils.htmlToPdf(orderContent, header, footer);
			FileUpDownUtils.setDownloadResponseHeaders(response, order.getNo() + ".pdf");
			FileUpDownUtils.downloadFile(file, response);
		} catch (Exception e) {
			LOGGER.error("download", e);
		}
		return null;
	}

	protected Map<String, Object> prepareOrderData(Integer orderId, HttpServletRequest request) {
		Packing order = packingManager.getObject(orderId);
		if (order.getRealTotalGrossWeight() != null) {
			order.setTotalGrossWeight(order.getRealTotalGrossWeight());
		}
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("entity", order);
		model.put("orderItems", order.getPackingItems());
		model.put("staticDomain", ProjectUtils.getFullCssThemePath());
		model.put("groupName", ApplicationConfig.getGroupName());
		String clientPoNo = orderManager.getAssociatesOrderClientPoNo(orderId, OrderAssociated.TYPE_PACKING);
		String orderNo = orderAssociatedManager.getPackingOrderStr(orderId);
		model.put("orderNo", orderNo);
		model.put("clientPoNo", clientPoNo);
		model.put("fontSize", ApplicationConfig.getFontSize());
		request.setAttribute("fontSize", ApplicationConfig.getFontSize());
		request.setAttribute("orderNo", orderNo);
		request.setAttribute("clientPoNo", clientPoNo);
		request.setAttribute("entity", order);
		request.setAttribute("staticDomain", ProjectUtils.getFullCssThemePath());
		request.setAttribute("groupName", ApplicationConfig.getGroupName());
		return model;
	}

	@Override
	public PageManager<Packing> getEntityManager() {
		return packingManager;
	}

	@Override
	public String getFileBasePath() {
		return "business/";
	}

}
